package com.boboPlanet.user.filter;

import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.boboPlanet.comm.context.LoginUserContext;
import com.boboPlanet.user.enums.ConstanceEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

import java.sql.Connection;


@Component
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
@Slf4j
public class UserMiddlerSqlCheckFilter implements Filter, Interceptor {

    @PostConstruct
    private void init() {}

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        HttpServletRequest request = (HttpServletRequest) servletRequest;
//        String url = request.getRequestURI();
//        if (ConstanceEnum.swagger_url.contains(url)){
//            filterChain.doFilter(servletRequest, servletResponse);
//        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        LoginUserContext.clear();
        Filter.super.destroy();
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        try {
            StatementHandler statementHandler = PluginUtils.realTarget(invocation.getTarget());
            BoundSql sql = statementHandler.getBoundSql();
            log.info("-------------- start execute sql -----------------");
            log.info("current execute sql is: {}",sql.getSql());
            log.info("current execute sql param is: {}",sql.getParameterObject());
            log.info("-------------- sql execute end -----------------");
        } catch (Throwable e) {
            log.error("planet sql filter execute error ==>"+e.getMessage(),e);
        }
        return invocation.proceed();
    }
}
